package com.liruo.enumconverter.core.gson;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class IntEnumTypeAdapterFactory implements TypeAdapterFactory {
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
        Class<? super T> rawType = typeToken.getRawType();
        if (Enum.class.isAssignableFrom(rawType) && rawType != Enum.class) {
            if (!rawType.isEnum()) {
                rawType = rawType.getSuperclass();
            }

            return new IntEnumTypeAdapter(rawType);
        } else {
            return null;
        }
    }

    private class IntEnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
        private final Map<Integer, T> ordinalToConstant;

        public IntEnumTypeAdapter(final Class<T> classOfT) {
            ordinalToConstant = new HashMap<>(classOfT.getEnumConstants().length);
            for (T enumConstant : classOfT.getEnumConstants()) {
                ordinalToConstant.put(enumConstant.ordinal(), enumConstant);
            }
        }

        public T read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            } else {
                int key = in.nextInt();
                return this.ordinalToConstant.get(key);
            }
        }

        public void write(JsonWriter out, T value) throws IOException {
            out.value(value == null ? null : value.ordinal());
        }
    }    
}